package com.example.netty.IO;

import sun.nio.ch.ThreadPool;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/** IO服务端
 * @author liupk
 * @date 2018/10/23
 */
public class IOServer {
    
    
    public static void main(String[] args) throws Exception{
    
        ServerSocket serverSocket;
        {
            try {
                serverSocket = new ServerSocket(8002);
                ExecutorService executorService = Executors.newCachedThreadPool();
                executorService.submit(new Runnable() {
                    @Override
                    public void run(){
                        while (true){
                            try {
                                Socket socket = serverSocket.accept();
                                Thread thread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        int len;
                                        byte[] data = new byte[1024];
                                        InputStream inputStream = null;
                                        try {
                                            inputStream = socket.getInputStream();
                                            // (3) 按字节流方式读取数据
                                            while ((len = inputStream.read(data)) != -1) {
                                                System.out.println(new String(data, 0, len));
                                            }
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                                thread.start();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
   
}